package com.dl698.axdr;

import com.dl698.asn1.axdr.AxdrType;
import com.dl698.util.ReverseByteArrayInputStream;
import com.dl698.util.ReverseByteArrayOutputStream;

/**
 * AxdrDateTimeS类
 * 实现日期时间S数据的编解码
 * 
 * @author wind
 * @version 1.1.1
 */
public class AxdrDateTimeS implements AxdrType {
    private byte[] value = new byte[7]; // 7字节日期时间S数据
    private byte[] dataCode = null;

    public AxdrDateTimeS() {
    }

    public AxdrDateTimeS(byte[] value) {
        if (value.length != 7) {
            throw new IllegalArgumentException("DateTimeS value must be 7 bytes");
        }
        System.arraycopy(value, 0, this.value, 0, 7);
    }

    public byte[] getValue() {
        return value;
    }

    public void setValue(byte[] value) {
        if (value.length != 7) {
            throw new IllegalArgumentException("DateTimeS value must be 7 bytes");
        }
        System.arraycopy(value, 0, this.value, 0, 7);
    }

    public byte[] getDataCode() {
        return dataCode;
    }

    public void setDataCode(byte[] dataCode) {
        this.dataCode = dataCode;
    }

    @Override
    public int decode(ReverseByteArrayInputStream input) {
        // 解码7个字节的日期时间S数据
        for (int i = 0; i < 7; i++) {
            this.value[i] = (byte) input.read();
        }
        return 7;
    }

    @Override
    public int encode(ReverseByteArrayOutputStream output) {
        // 编码7个字节的日期时间S数据
        try {
            for (int i = 0; i < 7; i++) {
                output.write(this.value[i]);
            }
        } catch (java.io.IOException e) {
            throw new RuntimeException(e);
        }
        return 7;
    }

    /**
     * 编码并保存
     * 
     * @param encodingSizeGuess 编码大小预估
     */
    public void encodeAndSave(int encodingSizeGuess) {
        ReverseByteArrayOutputStream revOStream = new ReverseByteArrayOutputStream();
        revOStream.setBufSize(encodingSizeGuess);
        this.encode(revOStream);
        this.dataCode = revOStream.getArray();
    }

    @Override
    public String toString() {
        return String.format("DateTimeS[%02X%02X%02X%02X%02X%02X%02X]",
                this.value[0] & 0xFF,
                this.value[1] & 0xFF,
                this.value[2] & 0xFF,
                this.value[3] & 0xFF,
                this.value[4] & 0xFF,
                this.value[5] & 0xFF,
                this.value[6] & 0xFF);
    }
}